package com.yf.exam.modules.exam.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yf.base.api.api.dto.BaseIdRespDTO;
import com.yf.course.modules.course.dto.ext.CourseDetailExtDTO;
import com.yf.course.modules.course.service.CourseService;
import com.yf.exam.modules.exam.dto.CreateAiExamDto;
import com.yf.exam.modules.exam.dto.OpenAIExamDTO;
import com.yf.exam.modules.exam.dto.QuestDto;
import com.yf.exam.modules.exam.service.ExamService;
import com.yf.exam.modules.exam.service.OpenCreateAiExamService;
import com.yf.exam.modules.tmpl.dto.OpenAITemplQuDTO;
import com.yf.exam.modules.tmpl.service.TmplService;

import com.yf.repo.modules.qu.dto.ext.QuDetailDTO;
import com.yf.repo.modules.qu.service.QuService;
import com.yf.repo.modules.repo.dto.ext.ChapterExtDTO;
import com.yf.repo.modules.repo.dto.ext.RepoDetailDTO;
import com.yf.repo.modules.repo.service.RepoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OpenCreateAiExamServiceImpl implements OpenCreateAiExamService {
    /**
     * 题库
     */
    @Autowired
    private RepoService repoService;
    /**
     * 试题
     */
    @Autowired
    private QuService quService;
    /**
     * 试卷
     */
    @Autowired
    private TmplService tmplService;

    @Autowired
    private ExamService examService;

    @Autowired
    private CourseService courseService;
    /**
     * 创建考试
     * @param createAiExamDto
     */
    @Override
    public void createPaper(CreateAiExamDto createAiExamDto) {
        createAiExamDto.setTotalScore(Integer.valueOf(createAiExamDto.getTotal_score().toString()));
        //过滤参数
        RepoDetailDTO repo = createAiExamDto.getRepo();
        repo=updateRepo(repo);

        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        SimpleDateFormat stm=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (createAiExamDto.getTemplType()==null){
            createAiExamDto.setTemplType(createAiExamDto.getTemplTitle());
        }
        if (createAiExamDto.getExamStartTime()==null){
            createAiExamDto.setExamStartTime(stm.format(currentDate));
        }
        if (createAiExamDto.getExamEndTime()==null){
            // 加上一个月
            calendar.add(Calendar.MONTH, 1);
            if (calendar.get(Calendar.DATE) > calendar.getActualMaximum(Calendar.DATE)) {
                calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
            }
            createAiExamDto.setExamEndTime(stm.format(calendar.getTime()));
        }
        if (createAiExamDto.getExamType()==null){
            createAiExamDto.setExamType("1");
        }
        if (createAiExamDto.getLimitNum()==null){
            createAiExamDto.setLimitNum(3);
        }
        createAiExamDto.setRepo(repo);


        String repoId;
        String chapterId;
            //创建题库
            Map<String, Object> stringObjectMap = repoService.saveById(createAiExamDto.getRepo());
            //获取题库id
            if (stringObjectMap.get("reqId")!=null&&stringObjectMap.get("chapterId")!=null){
                repoId=stringObjectMap.get("reqId").toString();
                chapterId=stringObjectMap.get("chapterId").toString();
            } else {
                chapterId = null;
                repoId=null;
            }
        List<QuDetailDTO> quList=new ArrayList<>();
        //获取试题
        List<QuestDto> questDtos = createAiExamDto.getQuestDtos();
        questDtos.stream().forEach(qudtos->{
//            题库种插入的试题id
            List<QuDetailDTO> quDTOS = qudtos.getQuDTOS();
            quDTOS.stream().forEach(item->{
                item.setChapterId(chapterId);
                item.setRepoId(repoId);
                String questType = qudtos.getQuestType();
                if (questType.equals("choose")){
                    //选择题
                    item.setQuType("1");
                    item.setQuScore(createAiExamDto.getChoose_score());
                } else if (questType.equals("fill")) {
                    //填空题
                    item.setQuType("5");
                    item.setQuScore(createAiExamDto.getFill_score());
                } else if (questType.equals("short_answer")) {
                    //简答题
                    item.setQuType("4");
                    item.setQuScore(createAiExamDto.getShort_answer_score());
                } else if (questType.equals("judge")) {
                    //判断题
                    item.setQuType("3");
                    item.setQuScore(createAiExamDto.getJudge_score());
                }
                item.setLevel("1");
                item.setContent(item.getQuestion());
                //封装试题
                String s = quService.saveById(item);
                item.setId(s);
                //封装试题类型
                quList.add(item);
            });
        });
        OpenAITemplQuDTO openAITemplQuDTO = new OpenAITemplQuDTO();
        openAITemplQuDTO.setQuesBankID(repoId);
        openAITemplQuDTO.setClassId(createAiExamDto.getClassId());
        openAITemplQuDTO.setQuestionIdList(quList.stream()
                .filter(item->item.getId()!=null)
                .map(item->{
                    Map<String, Object> map = new HashMap<>();
                    map.put("id",item.getId());
                    map.put("quType",item.getQuType());
                    map.put("score",item.getQuScore());
                    return map;
                })
                .collect(Collectors.toList()));
        openAITemplQuDTO.setTemplTitle(createAiExamDto.getTemplTitle());
        openAITemplQuDTO.setTemplType(createAiExamDto.getTemplType());
        openAITemplQuDTO.setClassId(createAiExamDto.getClassId());
        //自动创建试卷关联课程
        BaseIdRespDTO baseIdRespDTO = tmplService.openPaper(openAITemplQuDTO);
        OpenAIExamDTO openAIExamDTO=new OpenAIExamDTO();
        openAIExamDTO.setExamTitle(createAiExamDto.getExamTitle());
        openAIExamDTO.setExamStartTime(createAiExamDto.getExamStartTime());
        openAIExamDTO.setExamEndTime(createAiExamDto.getExamEndTime());
        openAIExamDTO.setExamType(createAiExamDto.getExamType());
        if (createAiExamDto.getPassGrade()==null){
            Integer totalScore = createAiExamDto.getTotalScore();
            if (totalScore==null){
                totalScore=0;
            }else {
                totalScore= (int) (totalScore*0.6);
            }
            openAIExamDTO.setPassGrade(totalScore);
        }else {
            openAIExamDTO.setPassGrade(createAiExamDto.getPassGrade());
        }
        openAIExamDTO.setLimitNum(createAiExamDto.getLimitNum());
        openAIExamDTO.setTotalScore(createAiExamDto.getTotalScore());
        openAIExamDTO.setTemplID(baseIdRespDTO.getId());
        //获取试卷id
        String s = examService.openAISaveExam(openAIExamDTO);
        CourseDetailExtDTO detail =new CourseDetailExtDTO();
        detail.setId(createAiExamDto.getClassId());
        detail.setRefExam(s);
        courseService.saveByExam(detail);
    }

    private CreateAiExamDto updateExam(CreateAiExamDto createAiExamDto) {
        Calendar calendar = Calendar.getInstance();
        Date currentDate = calendar.getTime();
        SimpleDateFormat stm=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (createAiExamDto.getTemplType()==null){
            createAiExamDto.setTemplType(createAiExamDto.getTemplTitle());
        }
        if (createAiExamDto.getExamStartTime()==null){
            createAiExamDto.setExamStartTime(stm.format(currentDate));
        }
        if (createAiExamDto.getExamEndTime()==null){
            // 加上一个月
            calendar.add(Calendar.MONTH, 1);
            Date newDate = calendar.getTime();
            createAiExamDto.setExamStartTime(stm.format(newDate));
        }
        if (createAiExamDto.getExamType()==null){
            createAiExamDto.setExamType("1");
        }
        if (createAiExamDto.getLimitNum()==null){
            createAiExamDto.setLimitNum(3);
        }
        return createAiExamDto;
    }

    private static RepoDetailDTO updateRepo(RepoDetailDTO repo){
        if (repo.getCatId()==null){
            //默认1848660252468187137
            repo.setCatId("1848660252468187137");
        }
        if (repo.getChapters()==null){
            ChapterExtDTO chapterExtDTO=new ChapterExtDTO();
            chapterExtDTO.setTitle("AI大模型");
            List<ChapterExtDTO>chapterExtDTOS=new ArrayList<>();
            chapterExtDTOS.add(chapterExtDTO);
            repo.setChapters(chapterExtDTOS);
        }
        if (repo.getId()==null){
            repo.setId("temp_"+ UUID.randomUUID());
        }
        if (repo.getIsExam()==null){
            repo.setIsExam(true);
        }
        if (repo.getIsTrain()==null){
            repo.setIsTrain(true);
        }
        if (repo.getOpenType()==null){
            repo.setOpenType(1);
        }
        if (repo.getPrice()==null){
            repo.setPrice(BigDecimal.valueOf(0));
        }
        if (repo.getRemark()==null){
            repo.setRemark("AI自动生成题库");
        }
        return repo;
    }
}
